import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login/index.vue'
import Layout from '@/views/Layout/index.vue'
import { GetToken } from '@/utils/storage.js'

const Home =() => import  ('@/views/Layout/Home/index.vue')
const Articles =() => import  ('@/views/Layout/Articles/index.vue')
const AddArticle =() => import  ('@/views/Layout/Articles/add.vue')
const EditArticle =() => import  ('@/views/Layout/Articles/edit')
const Pictures =() => import  ('@/views/Layout/Pictures/index.vue')
const NotFound =() => import  ('@/views/NotFound/index.vue')
const Comments =() => import  ('@/views/Layout/Comments')
const Fans =() => import  ('@/views/Layout/Fans')
const Settings =() => import  ('@/views/Layout/Settings')


Vue.use(VueRouter)

const routes = [
  {
    name: 'Login',
    path: '/login',
    component: Login
  },
  {
    name: 'Layout',
    path: '/',
    component: Layout,
    children: [
      {
        name: 'Home',
        path: '/',
        component: Home
      },
      {
        name: 'Articles',
        path: '/articles',
        component: Articles
      },
      {
        name: 'Pictures',
        path: '/pictures',
        component: Pictures
      },
      {
        name:'AddArticle',
        path:'/add-article',
        component:AddArticle
      },
      {
        name: 'EditArticle',
        path: '/edit-article/:id',
        component: EditArticle
      },
      {
        name:'Comments',
        path:'/comments',
        component:Comments
      },
      {
        name:'Fans',
        path:'/fans',
        component:Fans
      },
      {
        name: 'Settings',
        path: '/settings',
        component: Settings
      }
    ]

  },
  // 注意位置！
  {
    name: 'notfound',
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})
// 时机：在所有路由配置产生效果之前， 先进入beforeEach方法进行处理
// to -》要去的路由配置
// from -》从哪来
// next()-》需要根据情况调用

// 如果去登录，可以继续
// 如果有token，可以继续
// 否则，回到登录

router.beforeEach((to, from, next) => {
  // console.log({
  //   to, from, next
  // })
  const token = GetToken()

  if (to.path === '/login' || token) {
    next()
  } else {
    next('/login')
  }
})

export default router
